package com.ctriphotel.website.config;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;

@Component
public class ResourceFormatter{
    private JsonNode resourceMap;

    public ResourceFormatter(){
        ObjectMapper mapper = new ObjectMapper();
        File menifestFile = new File(Paths.get(".").toUri().normalize().getPath() + "assets/dist/webpack-manifest.json");

        try {
            resourceMap = mapper.readValue(menifestFile, JsonNode.class);
        } catch (IOException e) {
            resourceMap = null;
        }
    }

    public String format(String originPath){
        if (originPath.startsWith("js!")) {
            originPath = originPath.substring(originPath.indexOf("!") + 1) + ".js";
        }
        else if (originPath.startsWith("css!")) {
            originPath = originPath.substring(originPath.indexOf("!") + 1) + ".css";
        }
        String prefix = "";
        if ("false".equals(Constants.getNodeStatusValue("IS_DEV"))) {
            prefix = "/assets/dist/";
        }
        if(resourceMap != null && resourceMap.has(originPath)){
            return prefix + resourceMap.get(originPath).asText();
        }
        return prefix + originPath;
    }
}
